package life.sweet.community.controller;

import life.sweet.community.dto.CommentCreateDTO;
import life.sweet.community.dto.CommentDTO;
import life.sweet.community.dto.ResultDTO;
import life.sweet.community.enums.CommentTypeEnum;
import life.sweet.community.exception.CustomErrorCode;
import life.sweet.community.model.Comment;
import life.sweet.community.model.User;
import life.sweet.community.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @ResponseBody
    @RequestMapping(value = "comment", method = RequestMethod.POST)
    public Object post(@RequestBody CommentCreateDTO commentCreateDTO, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if(user == null) {
            return ResultDTO.errorOf(CustomErrorCode.NO_LOGIN);
        }
        /*User user = new User();
        user.setId(1L);*/

        if(StringUtils.isBlank(commentCreateDTO.getContent())) {
            return ResultDTO.errorOf(CustomErrorCode.CONTENT_IS_EMPTY);
        }
        Comment comment = new Comment();
        comment.setCommentator(user.getId());
        comment.setLikeCount(0L);
        comment.setContent(commentCreateDTO.getContent());
        comment.setParentId(commentCreateDTO.getParentId());
        comment.setType(commentCreateDTO.getType());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setGmtModified(System.currentTimeMillis());
        commentService.insert(comment,user);
        return ResultDTO.okOf();
    }

    @ResponseBody
    @RequestMapping(value = "/comment/{id}",method = RequestMethod.GET)
    public ResultDTO queryComments(@PathVariable(name = "id") Long id) {
        List<CommentDTO> dtoList = commentService.listByQuestionId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(dtoList);
    }


}
